import os
import json
import requests
from mcp.server.fastmcp import FastMCP
from datetime import datetime


mcp = FastMCP(host='0.0.0.0', port=9876)


@mcp.tool()
async def current_time():
    """获取北京时间的当前时间
    """
    now_time = datetime.now()
    return now_time.strftime('%Y-%m-%dT%H:%M:%S')


@mcp.tool()
async def address2geolocation(address: str) -> str:
    """地理编码：根据地理位置描述（如城市名、地名等）求解其地理经纬度坐标
    :param address: 地理位置描述（如城市名、地名等）
    :return: 地理经纬度坐标，格式为： "<经度>,<纬度>"
    """
    gaode_appkey = os.environ['GAODEAPPKEY']
    url = f'https://restapi.amap.com/v3/geocode/geo?address={address}&output=JSON&key={gaode_appkey}'

    try:
        res = requests.get(url)
    except Exception as e:
        return str(e)

    if res.status_code != 200:
        return res.text

    result = json.loads(res.text)
    return result['geocodes'][0]['location']


@mcp.tool()
async def weather_forecast(location: str) -> str:
    """天气预报： 根据地理经纬度坐标预测当地三天内天气情况
    :param location: 地理经纬度坐标，格式为： "<经度>,<纬度>"
    :return: 天气预报结果，JSON格式的字符串
    """
    caiyun_appkey = os.environ['CAIYUNAPPKEY']
    url = f'https://api.caiyunapp.com/v2.6/{caiyun_appkey}/{location}/daily?dailysteps=3'

    try:
        res = requests.get(url)
    except Exception as e:
        return str(e)

    return res.text


if __name__ == '__main__':
    mcp.run(transport='streamable-http')
